﻿using Infrastructure;
using Infrastructure.Data.Contexts;
using Shared.Configuration;
using Shared.Logging;
using WebApi.BuilderExtensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

//注册配置内容
builder.Services.Configure<DatabaseSettings>(
    builder.Configuration.GetSection(nameof(DatabaseSettings)));

builder.Services.Configure<LoggingSettings>(
    builder.Configuration.GetSection(nameof(LoggingSettings)));

builder.Services.Configure<RabbitMqSettings>(
    builder.Configuration.GetSection(nameof(RabbitMqSettings)));

builder.Services.Configure<RedisSettings>(
    builder.Configuration.GetSection(nameof(RedisSettings)));

var dbSettings = builder.Configuration
    .GetSection(nameof(DatabaseSettings))
    .Get<DatabaseSettings>()
    ?? throw new InvalidOperationException("Database settings missing.");

var logSettings = builder.Configuration
    .GetSection(nameof(LoggingSettings))
    .Get<LoggingSettings>()
    ?? throw new InvalidOperationException("log settings missing.");

// 注册服务
builder.Services
    .AddDatabaseContext(dbSettings)
    .AddInfrastructure(Path.Combine("configs", "permissions"))//TODO 文件路径要直接写config里面
    .AddRouting(options =>
    {
        options.LowercaseUrls = false;//小写路由
    })
    .AddSwaggerServices();

var app = builder.Build();

//自动迁移数据库
using (var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    //dbContext.Database.Migrate();
}

//添加swagger ui
app.UseSwaggerIfDevelopment(builder.Environment)
   .UseCors("AllowFrontend")
   .UseHttpsRedirection()
   .UseAuthorization();
app.MapControllers();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();